using BarManager.Core.ApplicationService.Interfaces;
using BarManager.Core.Entity;
using BarManager.UI.Web.Caching;
using BarManager.UI.Web.HtmlHelpers;
using BarManager.UI.Web.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace BarManager.UI.Web.Controllers
{
    [Authorize(Users = "admin")]
    public class ClienteController : BaseController<ClienteViewModel, Cliente, int>
    {
        public ClienteController(IClienteService service)
            : base(service)
        {
        }

        public override ActionResult Index(int id = 0)
        {
            ClienteViewModel model = new ClienteViewModel();
            if (id > 0)
            {
                //- Obtenemos los datos del cliente
                model.Entity = Service.Get(x => x.Id == id);                
                CacheManager.Set("ClienteViewModel", model);
                CacheManager.Set("DomicilioList", model.Entity.DomicilioList);
                return View(model);
            }
            return View();
        }      

        public override ActionResult List(string filter, int page = 1)
        {
            CacheManager.Clear();

            ClienteViewModel model = new ClienteViewModel
            {
                Entities = this.Service.GetAll().ToList().Where(x => filter == null || x.Nombre.Contains(filter)
                                                                 || x.Apellido.Contains(filter)
                                                                 || x.Telefono1.ToString().Contains(filter)
                                                                 || x.Telefono2.ToString().Contains(filter))
                                                         .OrderBy(x => x.NombreApellido)
                                                         .Skip((page - 1) * PageSize)
                                                         .Take(PageSize),
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = this.Service.GetAll().ToList().Where(x => filter == null || x.Nombre.Contains(filter)
                                                                       || x.Apellido.Contains(filter)
                                                                       || x.Telefono1.ToString().Contains(filter)
                                                                       || x.Telefono2.ToString().Contains(filter))
                                                                           .Count()
                }
            };
            model.Filter = filter;     
            return View(model);
        }

        public override ActionResult Save(ClienteViewModel model)
        {
            List<Domicilio> detalle = CacheManager.Get<List<Domicilio>>("DomicilioList");
            model.Entity.DomicilioList = detalle;

            //- Guarda o actualiza   
            if (model.Entity.Id == 0)
                ErrorList = Service.Add(model.Entity);
            else
                ErrorList = Service.Update(model.Entity);
            return ShowError(model, ErrorList);
        }

        [HttpPost]
        public PartialViewResult DetalleAdd(ClienteViewModel model)
        {
            //- Creamos nuevo item
            Domicilio item = model.Domicilio;

            //- Cachamos items agregados
            if (!CacheManager.IsSet("DomicilioList"))
            { CacheManager.Set("DomicilioList", new List<Domicilio>()); }

            //- Agregamos items al detalle si es que ya no existe
            CacheManager.Get<List<Domicilio>>("DomicilioList").Add(item);

            //- Actualizamos el detalle en cabecera y metemos en sesion al model
            model.Entity.DomicilioList = CacheManager.Get<List<Domicilio>>("DomicilioList");
            CacheManager.Set("ClienteViewModel", model);

            //- Devolvemos el model solo al detalle para refrezcar grilla
            return PartialView("_DomicilioList", CacheManager.Get<ClienteViewModel>("ClienteViewModel"));
        }

        [HttpPost]
        public PartialViewResult DetalleRemove(int id, string calle, int numero)
        {
            //- Eliminamos el Item
            if (id > 0)
                CacheManager.Get<List<Domicilio>>("DomicilioList")
                .RemoveAll(x => x.Id == id);
            else
                CacheManager.Get<List<Domicilio>>("DomicilioList")
                    .RemoveAll(x => x.Calle == calle && x.Numero == numero);

            //- Actualizamos los datos
            CacheManager.Get<ClienteViewModel>("ClienteViewModel").Entity.DomicilioList
                = CacheManager.Get<List<Domicilio>>("DomicilioList");

            //- Devolvemos el model solo al detalle para refrezcar grilla
            return PartialView("_DomicilioList", CacheManager.Get<ClienteViewModel>("ClienteViewModel"));
        }

        [HttpGet]
        public ActionResult DetalleEdit(int idCliente, int idDomicilio, string calle, int numero)
        {
            ClienteViewModel model = new ClienteViewModel();
            model.Entity = Service.Get(x => x.Id == idCliente);

            if (idDomicilio > 0)
                model.Domicilio = model.Entity.DomicilioList.FirstOrDefault(x => x.Id == idDomicilio);
            else
                model.Domicilio = model.Entity.DomicilioList.FirstOrDefault(x => x.Calle == calle && x.Numero == numero);

            //- Eliminamos de Cache el detalle a editar
            model.Entity.DomicilioList.Remove(model.Domicilio);
            CacheManager.Set("DomicilioList", model.Entity.DomicilioList);

            return View("Index", model);
        }
    }
}